/*
 * @Description: 流程中心模型
 * @Author: seadon & zhaoxiaoyang
 * @LastEditors: zhaoxiaoyang zhaoxiaoyang@byteluck.com
 * @Date: 2021-07-08 20:57:22
 * @LastEditTime: 2023-09-07 00:34:04
 */
import { Ref, ref, unref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { apiInit } from '@/services'
import { useLoading } from '@/hooks/useLoading'
import { useHomeContext } from '@/entry_desktop/views/Home/hooks/useContext'
import { IGroupList, IUseModelParams } from '../type'
import { i18n } from '@/locales'
import { client } from '@/utils'
import { isMoreTabs } from '@/utils/common'
import { useStore } from 'vuex'
import { iframePostMessage, isInnerIframePage } from '@/utils/tabInnerPage'

export default function useModel({ activeId, emit }: IUseModelParams) {
	const { $t } = i18n
	const api = apiInit()
	const groupListRef: Ref<IGroupList[]> = ref([])
	const groupListRefs: any = ref([])
	const applicationListRefs: any = ref([])
	const termination: any = ref(false) //判断是不是最后一页 false
	const defaultLoading = ref({ loading: false })
	const { getLoading, setLoading } = useLoading(defaultLoading)
	const { homeEmitter } = useHomeContext()
	const allTotal: any = ref(0)
	const allTotalLength: any = ref(0)
	const store = useStore()

	//应用中心分类-------新
	const applicationGroupList = async () => {
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.SelectGroupAppPrivateV2POST({})
		if (code === '000000') {
			groupListRefs.value = data
		} else {
			message.error(infoTip ?? '')
		}
	}

	//应用表单分组列表-------新
	const applyForGroupingList = async (
		page_index = 1,
		type = true,
		page_size = 6,
		keyword = ''
	) => {
		setLoading(type)
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.PageListAppPrivateV2POST({
			payload: {
				page: {
					page_index,
					page_size,
				},
				query: {
					keyword,
					enable_multiple_tab: isMoreTabs(),
				},
			},
		})

		if (code === '000000') {
			setLoading(false)
			if (type) {
				applicationListRefs.value = data?.rows
			} else {
				const arrayLength: any = data?.rows?.length
				if (arrayLength < page_size || !arrayLength) {
					termination.value = true
				}
				data?.rows?.forEach((category: any) => {
					unref(applicationListRefs).push(category)
				})
			}
		} else {
			message.error(infoTip ?? '')
		}
	}

	// 关闭分类筛选
	const applyForGroupingAllList = async (
		keyword = '',
		type = true,
		load_all = '0'
	) => {
		setLoading(type)
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.AllListAppPrivateV2POST({
			payload: {
				keyword: keyword,
				load_all: load_all,
			},
		})

		if (code === '000000') {
			setLoading(false)
			if (type) {
				applicationListRefs.value = data?.rows
				allTotal.value = data?.page?.total
				allTotalLength.value = data?.rows?.length
			} else {
				const arrayLength: any = data?.rows?.length
				data?.rows?.forEach((category: any) => {
					unref(applicationListRefs).push(category)
				})
			}
		} else {
			message.error(infoTip ?? '')
		}
	}

	//应用表单单个分组的列表------新
	const allLoading = ref(false)
	const fetchAppList = async (keyword = '', id = '') => {
		allLoading.value = true

		const {
			code,
			data,
			message: infoTip,
		} = await api.default.ListAppPrivateV2POST({
			payload: {
				keyword,
				group_id: id,
				enable_multiple_tab: isMoreTabs(),
			},
		})
		allLoading.value = false

		if (code === '000000') {
			if (unref(activeId)) {
				applicationListRefs.value = data
			} else {
				applicationListRefs.value = unref(applicationListRefs).map(
					(item: any) => {
						if (item.group_id === id) {
							const newData: any = data
							item = newData[0]
						}
						return item
					}
				)
			}
		} else {
			message.error(infoTip ?? '')
		}
	}
	const fetchAllAppList = async (keyword = '', type = true, load_all = '1') => {
		setLoading(type)
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.AllListAppPrivateV2POST({
			payload: {
				keyword: keyword,
				load_all: load_all,
			},
		})

		if (code === '000000') {
			setLoading(false)
			if (type) {
				applicationListRefs.value = data?.rows
				allTotal.value = data?.page?.total
				allTotalLength.value = data?.rows?.length
			} else {
				const arrayLength: any = data?.rows?.length
				// if (arrayLength < page_size || !arrayLength) {
				// 	termination.value = true
				// }
				data?.rows?.forEach((category: any) => {
					unref(applicationListRefs).push(category)
				})
			}
		} else {
			message.error(infoTip ?? '')
		}
	}
	// 搜索 应用表单分组列表(全量)
	const fetchGroupList = async (keyword = '', type = false) => {
		setLoading(true)
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.GroupListAppPrivateV2POST({
			payload: {
				keyword,
				enable_multiple_tab: isMoreTabs(),
			},
		})
		setLoading(false)
		applicationListRefs.value = []
		if (code === '000000') {
			data?.forEach(category => {
				unref(applicationListRefs).push(category)
			})
		} else {
			message.error(infoTip ?? '')
		}
	}

	// 收藏/取消收藏
	const saveFavorite = async (id: string, type = '0', group_id: string) => {
		const res = await api.default.SaveCollectUserPrivateV2POST({
			payload: {
				op_type: type,
				resource_id: id,
			},
		})
		if (res.code === '000000') {
			// applicationListRefs.value = []
			// emit && emit('onUpdateList')

			message.success(
				type === '0'
					? $t('pages.home.removed', '移除成功')
					: $t('pages.home.successfully', '收藏成功')
			)
			homeEmitter.emit('custom:fetchFavoriteList')
		} else {
			message.error(
				res.message || type === '0'
					? $t('pages.home.removedFailed', '移除失败')
					: $t('pages.home.favoriteFailed', '收藏失败')
			)
		}
		return res
	}
	const appLauncher = computed(
		() => store.state.tenant?.tenant_auth?.app_launcher === 1
	)
	// 保存最近访问
	const saveRecent = async (item: any) => {
		console.log(item, 'itemitemitem')
		if (isInnerIframePage()) {
			iframePostMessage(item, 'appCenter')
		} else {
			let url = item.form_url
			// let url = item.form_url.replace('/apps', 'http://localhost:8081')
			// 若开启启动器，点击应用后为当前页面跳转；没开启启动器，则为新页面跳转
			/* let target = localStorage.getItem('tenantDetail')
				? JSON.parse(localStorage.getItem('tenantDetail') || '').data
						.tenant_auth.app_launcher
				: undefined
			let targetWindow = client.openWindow(
				url + `?appLauncher=${appLauncher.value}`,
				target ? '_self' : undefined
			) */
			let targetWindow
			if(url.indexOf('?')>-1){
				targetWindow = client.openWindow(
					url + `&appLauncher=${appLauncher.value}`
				)
			}else{
				targetWindow = client.openWindow(
					url + `?appLauncher=${appLauncher.value}`
				)
			}
			iframePostMessage(item, 'appCenter', targetWindow)
		}
		const res = await api.default.SaveRecentPrivateV2POST({
			payload: { resource_id: item.fb_key },
		})
		homeEmitter.emit('custom:fetchRecentList')
		return res.data
	}

	const fetchList = (keyword: string, typeId: string) => {
		if (typeId) {
			//切换应用
			fetchAppList(keyword, typeId)
		} else if (!typeId && !keyword) {
			//全部应用
			applyForGroupingList()
		} else if (keyword) {
			//全部应用 搜索全量
			fetchGroupList(keyword)
		}
	}

	const getTenantCustomConfigMap = async () => {
		const res =
			JSON.parse(localStorage.getItem('tenantDetail') || '') ||
			(await api.baseAuto.GetTenantDetailTenantPublicApiPOST({}))
		return res?.data?.tenant_custom_config_map
	}

	return {
		applyForGroupingList,
		applicationGroupList,
		groupListRef,
		groupListRefs,
		applicationListRefs,
		applyForGroupingAllList,
		termination,
		getLoading,
		fetchList,
		fetchAppList,
		fetchAllAppList,
		fetchGroupList,
		saveFavorite,
		saveRecent,
		allLoading,
		allTotal,
		allTotalLength,
		getTenantCustomConfigMap,
	}
}
